<template>
  <div class="search">
    <!-- 1.0 头部搜索框 -->
    <div class="header">
      <van-search
        v-model.trim="keyword"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
      >
        <template #left>
          <i @click="$router.back()" class="iconfont iconjiantou"></i>
        </template>
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </div>
    <!-- 2.0 历史记录和热门搜索 -->
    <div class="group" v-show="!searchList.length">
      <div class="title">
        <h3>历史记录</h3>
        <van-icon @click="keywordArr = []" name="delete-o" />
      </div>
      <div class="list">
        <span class="item" v-for="(item, index) in keywordArr" :key="index">{{
          item
        }}</span>
      </div>
    </div>
    <!-- 3.0 搜索结果面板 -->
    <div class="result" v-show="searchList.length">
      <router-link
        class="item"
        v-for="item in searchList"
        :key="item.id"
        :to="`/article/${item.id}`"
      >
        <span class="text">{{ item.title }}</span>
        <i class="iconfont iconjiantou1"></i>
      </router-link>
    </div>
  </div>
</template>

<script>
import { getPostSearchAPI } from "../apis/news";
import { getSearchKeyword, setSearchKeyword } from "../utils/localData";
export default {
  data() {
    return {
      keyword: "",
      searchList: [],
      //   从本地存储中获取搜索历史记录
      keywordArr: getSearchKeyword(),
    };
  },
  methods: {
    // 点击搜索按钮/按回车键/手机键盘右下角按钮
    async onSearch() {
      console.log("点击了搜索按钮", this.keyword);
      // 判断是否为空
      if (this.keyword === "") {
        return this.$toast.fail("请输入搜索关键词");
      }
      //   按搜索后，返回
      this.keywordArr.unshift(this.keyword);
      this.keywordArr = [...new Set(this.keywordArr)];
      if (this.keywordArr.length >= 10) {
        this.keywordArr.length = 10;
      }
      // 发送请求获取搜索结果
      const res = await getPostSearchAPI({
        keyword: this.keyword,
      });
      // console.log(res);
      // 保存搜索结果
      this.searchList = res.data.data;
    },
  },
  watch: {
    keyword() {
      // 如果关键词为空
      if (this.keyword === "") {
        // 清空数组，隐藏搜索结果面板
        this.searchList = [];
      }
    },
    // 监听关键数组
    keywordArr() {
      // 搜索关键词数组有变化，就存储到本地
      setSearchKeyword(this.keywordArr);
    },
  },
};
</script>

<style lang="less" scoped>
.group {
  padding: 10px;
  .title {
    font-size: 16px;
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
  }

  .list {
    display: flex;
    flex-wrap: wrap;
    .item {
      padding: 5px;
      font-size: 13px;
      margin-right: 10px;
      border: 1px solid #ccc;
    }
  }
}
.result {
  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #ccc;
  }
}
</style>